import type { ActionFn } from '../interceptorActionHandler'
import type { IMResponse } from '../types'

/**
 * 错误处理器
 * @param {object} response 响应上下文
 * @returns {object}
 */
export const errorHandler: ActionFn = (response: IMResponse) => {
  const handler = () => {
    if (+response.statusCode !== 200) {
      uni.showToast({
        title: `服务异常，请稍后再试：${response.statusCode}`,
        icon: 'none',
      })
    } else if (+response.data.code !== 200 && +response.data.code !== 1001) {
      uni.showToast({
        title: response.data.msg,
        icon: 'none',
      })
    }
    return response
  }

  let checkHandle = true
  const { request } = response
  if (request.plugin?.errorHandler === false) {
    checkHandle = false
  }

  return { checkHandle, value: handler }
}
